﻿namespace VantCommands {
    interface DialogParam extends AdvancedSettingParam {
        title: string;
        theme: string;
        message: string;
        showConfirmButton: boolean;
        confirmButtonText: string;
        confirmButtonColor: string;
        showCancelButton: boolean;
        cancelButtonText: string;
        cancelButtonColor: string;
        DialogResult: string;
        AdvancedSetting: AdvancedSettingParam;
        beforeClose: Function;
    }

    interface AdvancedSettingParam {
        width: number;
        overlay: boolean;
        messageAlign: string;
        closeOnPopstate: boolean;
        closeOnClickOverlay: boolean;
        allowHtml: boolean;
        distinguishCancelAndClose: boolean;
    }

    export class DialogMessage extends Forguncy.Plugin.CommandBase {

        public execute() {
            let param = <DialogParam>this.CommandParam;
            param = {
                showConfirmButton: !!param.showConfirmButton,
                showCancelButton: !!param.showCancelButton,
                ...param,
                overlay: !!param.AdvancedSetting.overlay,
                closeOnPopstate: !!param.AdvancedSetting.closeOnPopstate,
                closeOnClickOverlay: !!param.AdvancedSetting.closeOnClickOverlay,
                ...param.AdvancedSetting
            };
            Forguncy.PageBuilder.hidePageLoadingCover();
            const clone = <DialogParam>{ ...param };
            Reflect.deleteProperty(clone, "$type");
            clone.title = this.evaluateFormula(clone.title)?.toString();
            clone.message = this.evaluateFormula(clone.message)?.toString();
            clone.confirmButtonColor = Forguncy.ConvertToCssColor(clone.confirmButtonColor);
            clone.cancelButtonColor = Forguncy.ConvertToCssColor(clone.cancelButtonColor);
            clone.beforeClose = (action: "confirm" | "cancel" | "close") => {
                window.vant.Dialog.close();
                Vue.nextTick(() => {
                    let result = action;
                    if (action === undefined) {
                        result = param.AdvancedSetting.distinguishCancelAndClose ? "close" : "cancel";
                    }
                    Forguncy.CommandHelper.setVariableValue(param.DialogResult, result);
                    this.CommandExecutingInfo.suspend = false;
                });
            };
            window.vant.Dialog(clone);

            this.CommandExecutingInfo.suspend = true;
        }
    }
}

Forguncy.Plugin.CommandFactory.registerCommand("Vant.Commands.Dialog, Vant", VantCommands.DialogMessage);